package cn.xshi.iot.live.worker;

import cn.xshi.iot.live.util.ApplicationContextUtil;
import cn.xshi.iot.live.util.CacheUtil;
import cn.xshi.iot.live.service.LiveService;
import cn.xshi.iot.live.model.CameraEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
 * @Desc 录制线程保存活
 * @Author 邓纯杰
 * @CreateTime 2012-12-12 12:12:12
 */
@Slf4j
public class KeepAliveTranscribeWorker extends Thread{

    /**待处理队列*/
    public static Map<String, CameraEntity> keepAliveTranscribeMap = new ConcurrentHashMap<String, CameraEntity>();

    public int errIndex=0;//错误计数

    public volatile int stopIndex=0;//安全停止线程标记

    /**
     *
     * @param cameraEntity
     */
    public static void put(CameraEntity cameraEntity){
        log.info("录制视频保活线程开始放入缓存：{}",cameraEntity.getStream());
        keepAliveTranscribeMap.put(cameraEntity.getStream(),cameraEntity);
        log.info("录制视频保活线程结束放入缓存：{}",cameraEntity.getStream());
    }

    /**
     *
     */
    @Override
    public void run() {
        for(;errIndex==0;) {
            try {
                if(CollectionUtils.isEmpty(keepAliveTranscribeMap)) {
                    continue;
                }
                Iterator iter = keepAliveTranscribeMap.entrySet().iterator();
                while(iter.hasNext()) {
                    Map.Entry<String, CameraEntity> entry = (Map.Entry<String, CameraEntity>) iter.next();
                    CameraEntity cameraEntity = entry.getValue();
                    log.info("录制视频,设备编号："+cameraEntity.getStream()+",ErrorCount："+cameraEntity.getErrorCount());
                    if(null != CacheUtil.transcribeMap && null != CacheUtil.transcribeMap.get(entry.getKey())){
                        //如果缓存中已经有了 说明该任务在其它地方已经加入执行了
                        log.info("录制视频已存在，ID号："+entry.getKey());
                        keepAliveTranscribeMap.remove(entry.getKey());
                        continue;
                    }
                    if(cameraEntity.getErrorCount()>100){
                        //当错误大于100次则说明该设备无用了
                        log.info("录制视频终止连接，原因始终无法连接成功，该设备无效，ID号："+entry.getKey());
                        keepAliveTranscribeMap.remove(entry.getKey());
                        continue;
                    }
                    //重启任务
                    log.info("录制视频保活线程已重启任务开始，ID号："+entry.getKey());
                    LiveService liveService = ApplicationContextUtil.getBean(LiveService.class);
                    liveService.startTranscribe(cameraEntity);
                    keepAliveTranscribeMap.remove(entry.getKey());//加入保活移除该元素
                    log.info("录制视频保活线程已重启任务完毕，ID号："+entry.getKey());
                    Thread.sleep(1000);
                }
            }catch (Exception e){
                log.error("录制视频保活线程终止{}：",e);
            }
        }
    }
}
